/*
 * @Author: wuzhouhai wzh200x@126.com
 * @Date: 2024-03-20 10:50:50
 * @LastEditors: wuzhouhai wzh200x@126.com
 * @LastEditTime: 2025-01-03 17:22:24
 * @FilePath: \dwys_web\extensions\phoenix-plugin-client\assets\core\http\PhoenixHttpClient.ts
 * @Description:
 */
import { InputBase } from '../dto/input-base';
import { IPlatform } from '../interface/platform.interface';
import { UtilsHttp } from '../utils/Utils.Http';
// import flyio from "flyio";
type Result<T> = {
    code: number;
    message: string;
    data: T;
};

export class PhoenixHttpClient {
    private secretKey: string;
    private platform: IPlatform;
    private host: string;
    private port: string;
    private isSSL: boolean;

    constructor(platform: IPlatform, host: string, port: string, isSSL: boolean, secretKey?: string) {
        this.host = host;
        this.port = port;
        this.isSSL = isSSL;
        this.platform = platform;
        this.setBaseUrl(host, port, isSSL);
        this.secretKey = secretKey ?? '';
    }

    setBaseUrl(host: string, port: string, isSSL: boolean) {
        this.host = host;
        this.port = port;
        this.isSSL = isSSL;
        this.setPlatformBaseUrl();
    }

    setPlatformBaseUrl(){
        if (this.port == null || this.port == '' || this.port == '80' || this.port == '443' || this.port == '0') {
            if (this.isSSL) {
                this.platform.setBaseUrl(`https://${this.host}`);
            } else {
                this.platform.setBaseUrl(`http://${this.host}`);
            }
        } else {
            if (this.isSSL) {
                this.platform.setBaseUrl(`https://${this.host}:${this.port}`);
            } else {
                this.platform.setBaseUrl(`http://${this.host}:${this.port}`);
            }
        }
    }

    public async requestPost<T = any>(url: string, data: InputBase, token?: string): Promise<any> {
        console.log('login requestPost:', url);
        this.setPlatformBaseUrl();
        let signObject:Record<string, any> = UtilsHttp.generateRequestSign(url, data, this.secretKey);
        signObject['data']['sign'] = signObject['sign'];
        return this.platform!.request('post', url, signObject['data'], token);
    }

    public async requestGet<T = any>(url: string, data: InputBase, token?: string): Promise<any> {
        this.setPlatformBaseUrl();
        let signObject:Record<string, any> = UtilsHttp.generateRequestSign(url, data, this.secretKey);
        signObject['data']['sign'] = signObject['sign'];
        return this.platform!.request('get', url, signObject['data'], token);
    }
}

